package com.crm.system.service.impl.opportunityManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.opportunityManager.Opportunity;
import com.crm.model.entity.opportunityManager.OpportunityCollaborator;
import com.crm.model.entity.opportunityManager.OpportunityContact;
import com.crm.model.entity.opportunityManager.OpportunityProduct;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.qo.opportunityManager.AddOpportunityQO;
import com.crm.model.qo.opportunityManager.OpportunityQO;
import com.crm.model.qo.opportunityManager.OpportunityStatusQO;
import com.crm.model.vo.cluePoolManager.ContactDetailFollowVO;
import com.crm.model.vo.datasearch.DataSearchResultVO;
import com.crm.model.vo.opportunityManager.*;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.opportunityManager.OpportunityCollaboratorDbService;
import com.crm.service.opportunityManager.OpportunityContactDbService;
import com.crm.service.opportunityManager.OpportunityDbService;
import com.crm.service.opportunityManager.OpportunityProductDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import com.crm.system.service.opportunityManager.OpportunityCollaboratorService;
import com.crm.system.service.opportunityManager.OpportunityContactService;
import com.crm.system.service.opportunityManager.OpportunityService;
import com.crm.system.service.permissionManagement.SysCompanyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * bj
 * 商机管理
 */
@Service
public class OpportunityServiceImpl implements OpportunityService {

    @Autowired
    private OpportunityDbService opportunityDbService;

    @Autowired
    private OpportunityProductDbService opportunityProductDbService;

    @Autowired
    private OpportunityContactService opportunityContactService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    private OpportunityCollaboratorService opportunityCollaboratorService;

    @Autowired
    private OpportunityCollaboratorDbService opportunityCollaboratorDbService;

    @Autowired
    private SysCompanyDbService sysCompanyDbService;

    @Autowired
    private ClueFollowDbService clueFollowDbService;

    private static String superAccountId = "71902468-8dee-4e30-b554-456d2140c7d9";

    @Autowired
    private CustomerContractDbService customerContractDbService;

    /**
     * 商机管理信息
     * @param pageIndex
     * @param pageSize
     * @param opportunityQO
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<OpportunityVO> selectOpportunityVoList(Integer pageIndex, Integer pageSize, OpportunityQO opportunityQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        Integer count = 0;

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        //增加删除状态查询条件(0:正常;1:已删除)
        opportunityQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        /*if(!StringUtils.isBlank(opportunityQO.getEstimatedSigningTime())) {
            String estimatedSigningTime = opportunityQO.getEstimatedSigningTime();
            String startDate = estimatedSigningTime.substring(0, 10);
            String endDate = estimatedSigningTime.substring(estimatedSigningTime.indexOf("至") + 2, estimatedSigningTime.length());
            opportunityQO.setStartDate(startDate);
            opportunityQO.setEndDate(endDate);
        }*/

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(opportunityQO.getDateType())) {
            if ("thisWeek".equals(opportunityQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(opportunityQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
        }

        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "customerName":
                {
                    order.append("b.customer_name ").append(sortOrder);//客户名称
                }
                break;
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                case "opportunityStatus":
                {
                    order.append("a.opportunity_status ").append(sortOrder);
                }
                break;
                case "estimatedSigningTime":
                {
                    order.append("a.estimated_signing_time ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<OpportunityVO> opportunityList = new ArrayList<OpportunityVO>();
        if("0".equals(opportunityQO.getBs())) {
            if(rs) {
                //超级管理员
                opportunityList = opportunityDbService.selectOpportunityGlyList(opportunityQO, order.toString(),dateUnit);
            }else {
                //普通管理员
                //opportunityQO.setCompanyId(userAccount.getCompanyId());
                opportunityQO.setAccountId(userAccount.getCompanyId());
                opportunityList = opportunityDbService.selectOpportunityFgsList(opportunityQO, order.toString(),dateUnit);
            }
        }else {
            //普通用户
            opportunityQO.setAccountId(userAccount.getAccountId());
            opportunityList = opportunityDbService.selectOpportunityPtyhList(opportunityQO, order.toString(),dateUnit);
        }

        PageInfo<OpportunityVO> pageInfo = new PageInfo<OpportunityVO>(opportunityList);
        return new DhPageInfo<OpportunityVO>(pageInfo, opportunityList);
    }

    @Override
    public List<Opportunity> selectOpportunityListByCustomerId(String customerId) {
        List<Opportunity> opportunityList = opportunityDbService.selectOpportunityListByCustomerId(customerId);
        return opportunityList;
    }


    /**
     * 商机状态统计
     * @param opportunityStatusQO dateType thisMonth 本月 thisQuarter 本季度  thisYear 本年
     * @param opportunityStatusQO bs 0管理端 1用户端
     * @param opportunityStatusQO name 公司id
     * @param opportunityStatusQO startTime 开始时间
     * @param opportunityStatusQO endTime 结束时间
     * @return
     */
    @Override
    public List<Integer> oppStatusStatistics(OpportunityStatusQO opportunityStatusQO) {
        List<OpportunityStatusVO> list = new ArrayList<>();
        List<Integer> numList = Arrays.asList(0, 0, 0, 0, 0, 0, 0);

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());


        Integer dateUnit = 0;
        if (!StringUtils.isBlank(opportunityStatusQO.getDateType())) {
            if ("thisMonth".equals(opportunityStatusQO.getDateType())) {
                //本月
                dateUnit = 1;
            }
            if ("thisQuarter".equals(opportunityStatusQO.getDateType())) {
                //本季度
                dateUnit = 2;
            }
            if ("thisYear".equals(opportunityStatusQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("thisLastMonth".equals(opportunityStatusQO.getDateType())) {
                //上个月
                dateUnit = 4;
            }
            if("section".equals(opportunityStatusQO.getDateType())) {
                //区间
                dateUnit = 5;
            }
            if("thisWeek".equals(opportunityStatusQO.getDateType())) {
                //区间
                dateUnit = 6;
            }

        }

        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        String accountId = "";
        if("0".equals(opportunityStatusQO.getBs())) {
            if(rs) {
                number = 0;
            }else {
                //普通管理员
                number = 1;
                opportunityStatusQO.setName(userAccount.getCompanyId());
            }
        }else {
            //普通用户
            number = 2;
            opportunityStatusQO.setName(userAccount.getAccountId());
        }

        if(superAccountId.equals(userAccount.getAccountId())){
            if(!StringUtils.isBlank(opportunityStatusQO.getName())){
                 list = opportunityDbService.oppStatusStatistics(opportunityStatusQO.getName(),number,dateUnit,opportunityStatusQO.getStartTime(),opportunityStatusQO.getEndTime(),superAccountId);
            }
            return numList;
        }else{
            list = opportunityDbService.oppStatusStatistics(opportunityStatusQO.getName(),number,dateUnit,opportunityStatusQO.getStartTime(),opportunityStatusQO.getEndTime(),superAccountId);
            numList = calculation(list, numList);
            return numList;
        }





    }


    /**
     * 商机状态统计
     * @param opportunityStatusQO dateType thisMonth 本月 thisQuarter 本季度  thisYear 本年
     * @param opportunityStatusQO bs 0管理端 1用户端
     * @param opportunityStatusQO name 公司id
     * @param opportunityStatusQO startTime 开始时间
     * @param opportunityStatusQO endTime 结束时间
     * @return
     */
    @Override
    public List<Integer> oppStatusStatisticsAdmin(OpportunityStatusQO opportunityStatusQO) {
        List<OpportunityStatusVO> list = new ArrayList<>();
        List<Integer> numList = Arrays.asList(0, 0, 0, 0, 0, 0, 0);

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());


        Integer dateUnit = 0;
        if (!StringUtils.isBlank(opportunityStatusQO.getDateType())) {
            if ("thisMonth".equals(opportunityStatusQO.getDateType())) {
                //本月
                dateUnit = 1;
            }
            if ("thisQuarter".equals(opportunityStatusQO.getDateType())) {
                //本季度
                dateUnit = 2;
            }
            if ("thisYear".equals(opportunityStatusQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("thisLastMonth".equals(opportunityStatusQO.getDateType())) {
                //上个月
                dateUnit = 4;
            }
            if("section".equals(opportunityStatusQO.getDateType())) {
                //区间
                dateUnit = 5;
            }
            if("thisWeek".equals(opportunityStatusQO.getDateType())) {
                //区间
                dateUnit = 6;
            }

        }
        list = opportunityDbService.oppStatusStatisticsAdmin(dateUnit,opportunityStatusQO.getStartTime(),opportunityStatusQO.getEndTime(),opportunityStatusQO.getAccountId());
        numList = calculation(list, numList);
        return numList;
    }
    /**
     * 整合numList集合
     * @param list
     * @param numList
     * @return
     */
    public List<Integer> calculation(List<OpportunityStatusVO> list,List<Integer> numList){
        Map<String,Integer> map =
                list.stream().collect(Collectors.toMap(OpportunityStatusVO::getOpportunityStatus, OpportunityStatusVO::getStatusNumber,
                        (key1,key2) ->key2));

        for (int i = 0; i < numList.size(); i++) {
            if(map.containsKey(i+1+"")){
                Integer aa = map.get(i+1+"");
                numList.set(i,aa);
            }
        }
        return numList;
    }

    /**
     * 商机产品比重
     * @param dateType thisMonth 本月 thisQuarter 本季度  thisYear 本年
     * @param bs 0管理端 1用户端
     * @return
     */
    @Override
    public List<OpportunityProductVO> oppProductStatistics(String dateType,String bs) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String name =null;

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 1;
            }
            if ("thisQuarter".equals(dateType)) {
                //本季度
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
            if ("thisLastMonth".equals(dateType)) {
                //上个月
                dateUnit = 4;
            }
        }

        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        if("0".equals(bs)) {
            //普通管理员
            number = 1;
            name = userAccount.getCompanyId();
        }else {
            //普通用户
            number = 2;
            name = userAccount.getAccountId();
        }
        if(superAccountId.equals(userAccount.getAccountId())) {
            return new ArrayList<OpportunityProductVO>();
        }else {
            return opportunityDbService.oppProductStatistics(name,number,dateUnit,superAccountId);
        }

    }

    /**
     * 管理模块 --商机分布--商机列表
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param dateType thisMonth 本月 thisQuarter 本季度  thisYear 本年
     * @param bs 0管理端 1用户端
     * @return
     */
    @Override
    public DhPageInfo<OpportunityStatisticsVO> selectOppStatistics(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String dateType, String bs) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String name =null;

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 1;
            }
            if ("thisQuarter".equals(dateType)) {
                //本季度
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
            if ("thisLastMonth".equals(dateType)) {
                //上个月
                dateUnit = 4;
            }
        }

        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        if("0".equals(bs)) {
            //普通管理员
            number = 1;
            name = userAccount.getCompanyId();
        }else {
            //普通用户
            number = 2;
            name = userAccount.getAccountId();
        }

        List<OpportunityStatisticsVO> list = new ArrayList<>();

        if(!superAccountId.equals(userAccount.getAccountId())){
            list = opportunityDbService.selectOppStatistics(name,number,dateUnit,superAccountId);
        }

        PageInfo<OpportunityStatisticsVO> pageInfo = new PageInfo<OpportunityStatisticsVO>(list);
        return new DhPageInfo<OpportunityStatisticsVO>(pageInfo, list);

    }

    /**
     * 通过商机id带出来合同需要的数据
     * @param opportunityId 商机id
     * @return
     */
    @Override
    public OpportunityContractDetailVO opportunityContractDetail(String opportunityId) {
        return opportunityDbService.opportunityContractDetail(opportunityId);
    }

    /**
     * 管理员-商机状态统计
     * @param opportunityStatusQO dateType thisLastMonth 上月  thisMonth 本月 thisQuarter 本季度  thisYear 本年  section 区间
     * @param opportunityStatusQO startTime 起始时间
     * @param opportunityStatusQO endTime 截止时间
     * @return
     */
    @Override
    public Map<String,Object> adminOppStatusStatistics(OpportunityStatusQO opportunityStatusQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String name =null;

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(opportunityStatusQO.getDateType())) {
            if ("thisMonth".equals(opportunityStatusQO.getDateType())) {
                //本月
                dateUnit = 1;
            }
            if ("thisQuarter".equals(opportunityStatusQO.getDateType())) {
                //本季度
                dateUnit = 2;
            }
            if ("thisYear".equals(opportunityStatusQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("thisLastMonth".equals(opportunityStatusQO.getDateType())) {
                //上个月
                dateUnit = 4;
            }
            if("section".equals(opportunityStatusQO.getDateType())) {
                //区间
                dateUnit = 5;
            }
        }

        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        if(!rs){
            //普通管理员
            number = 1;
            name = userAccount.getCompanyId();
        }



        opportunityStatusQO.setNumber(number);
        opportunityStatusQO.setDateUnit(dateUnit);
        opportunityStatusQO.setName(name);
        //opportunityStatusQO.setSuperAccountId(superAccountId);


        List<OpportunityStatusVO> list = opportunityDbService.adminOppStatusStatistics(opportunityStatusQO);

        //公司名称
        List<String> companyList = new ArrayList<>();
        //状态个数
        List<Integer> numList = new ArrayList<>();
        for (OpportunityStatusVO opportunityStatusVO : list){
            companyList.add(opportunityStatusVO.getCompanyName());
            numList.add(opportunityStatusVO.getStatusNumber());
        }

        Map<String,Object> map = new HashMap<>();
        map.put("companyList",companyList);
        map.put("numList",numList);
        return map;
    }

    /**
     * 管理员-业绩排名
     * @param opportunityStatusQO dateType thisLastMonth 上月  thisMonth 本月 thisQuarter 本季度  thisYear 本年  section 区间
     * @param opportunityStatusQO startTime 起始时间
     * @param opportunityStatusQO endTime 截止时间
     * @return
     */
    @Override
    public List<PerformanceRankingVO> performanceRanking(OpportunityStatusQO opportunityStatusQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String name =null;

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(opportunityStatusQO.getDateType())) {
            if ("thisMonth".equals(opportunityStatusQO.getDateType())) {
                //本月
                dateUnit = 1;
            }
            if ("thisQuarter".equals(opportunityStatusQO.getDateType())) {
                //本季度
                dateUnit = 2;
            }
            if ("thisYear".equals(opportunityStatusQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("thisLastMonth".equals(opportunityStatusQO.getDateType())) {
                //上个月
                dateUnit = 4;
            }
            if("section".equals(opportunityStatusQO.getDateType())) {
                //区间
                dateUnit = 5;
            }
        }

        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;

        if(rs) {
            number = 0;
            name = userAccount.getAccountId();
        }else {
            //普通管理员
            number = 1;
            name = userAccount.getCompanyId();
        }
        opportunityStatusQO.setNumber(number);
        opportunityStatusQO.setDateUnit(dateUnit);
        opportunityStatusQO.setName(name);
        //opportunityStatusQO.setSuperAccountId(superAccountId);



        List<PerformanceRankingVO> list = opportunityDbService.performanceRanking(opportunityStatusQO);
        return list;
    }

    /**
     * 统计商机数据一览
     * @return
     */
    @Override
    public Map<String, OpportunityDataVO> oppDataStatistics() {
        Map<String, OpportunityDataVO> map = new HashMap<>();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        String companyId =null;

        if(rs) {
            number = 0;
            companyId = userAccount.getAccountId();
        }else {
            //普通管理员
            number = 1;
            companyId = userAccount.getCompanyId();
        }
        OpportunityDataVO lastMonthOpp = new OpportunityDataVO();
        OpportunityDataVO thisWeekOpp = new OpportunityDataVO();
        OpportunityDataVO thisMonthOpp = new OpportunityDataVO();

        //上月
        //成交额度
        BigDecimal lastMonthTransactionAmount = opportunityDbService.selectTransactionAmount(1,number,companyId,superAccountId);
        lastMonthOpp.setTransactionAmount(lastMonthTransactionAmount);

        //会员新增
        Integer lastMonthNewMembers = opportunityDbService.selectNewMembers(1,number,companyId,superAccountId);
        lastMonthOpp.setNewMembers(lastMonthNewMembers);

        //商机新增
        Integer lastMonthNewOpportunity = opportunityDbService.selectNewOpportunity(1,number,companyId,superAccountId);
        lastMonthOpp.setNewOpportunity(lastMonthNewOpportunity);

        //赢单新增
        Integer lastMonthNewWinOrder = opportunityDbService.selectNewWinOrder(1,number,companyId,superAccountId);
        lastMonthOpp.setNewWinOrder(lastMonthNewWinOrder);

        //待回款额度
        BigDecimal lastMonthAmountReturned = opportunityDbService.selectAmountReturned(1,number,companyId,superAccountId);
        lastMonthOpp.setAmountReturned(lastMonthAmountReturned);

        //联系人新增
        Integer lastMonthNewContact = opportunityDbService.selectNewContact(1,number,companyId,superAccountId);
        lastMonthOpp.setNewContact(lastMonthNewContact);

        //电话量新增
        Integer lastMonthNewCallVolume = opportunityDbService.selectNewCallVolume(1,number,companyId,superAccountId);
        lastMonthOpp.setNewCallVolume(lastMonthNewCallVolume);

        //上月
        map.put("lastMonth",lastMonthOpp);

        //本周
        //成交额度
        BigDecimal thisWeekTransactionAmount = opportunityDbService.selectTransactionAmount(2,number,companyId,superAccountId);
        thisWeekOpp.setTransactionAmount(thisWeekTransactionAmount);

        //会员新增
        Integer thisWeekNewMembers = opportunityDbService.selectNewMembers(2,number,companyId,superAccountId);
        thisWeekOpp.setNewMembers(thisWeekNewMembers);

        //商机新增
        Integer thisWeekNewOpportunity = opportunityDbService.selectNewOpportunity(2,number,companyId,superAccountId);
        thisWeekOpp.setNewOpportunity(thisWeekNewOpportunity);

        //赢单新增
        Integer thisWeekNewWinOrder = opportunityDbService.selectNewWinOrder(2,number,companyId,superAccountId);
        thisWeekOpp.setNewWinOrder(thisWeekNewWinOrder);

        //待回款额度
        BigDecimal thisWeekAmountReturned = opportunityDbService.selectAmountReturned(2,number,companyId,superAccountId);
        thisWeekOpp.setAmountReturned(thisWeekAmountReturned);

        //联系人新增
        Integer thisWeekNewContact = opportunityDbService.selectNewContact(2,number,companyId,superAccountId);
        thisWeekOpp.setNewContact(thisWeekNewContact);

        //电话量新增
        Integer thisWeekNewCallVolume = opportunityDbService.selectNewCallVolume(2,number,companyId,superAccountId);
        thisWeekOpp.setNewCallVolume(thisWeekNewCallVolume);

        //本周
        map.put("thisWeek",thisWeekOpp);

        //本月
        //成交额度
        BigDecimal thisMonthTransactionAmount = opportunityDbService.selectTransactionAmount(3,number,companyId,superAccountId);
        thisMonthOpp.setTransactionAmount(thisMonthTransactionAmount);

        //会员新增
        Integer thisMonthNewMembers = opportunityDbService.selectNewMembers(3,number,companyId,superAccountId);
        thisMonthOpp.setNewMembers(thisMonthNewMembers);

        //商机新增
        Integer thisMonthNewOpportunity = opportunityDbService.selectNewOpportunity(3,number,companyId,superAccountId);
        thisMonthOpp.setNewOpportunity(thisMonthNewOpportunity);

        //赢单新增
        Integer thisMonthNewWinOrder = opportunityDbService.selectNewWinOrder(3,number,companyId,superAccountId);
        thisMonthOpp.setNewWinOrder(thisMonthNewWinOrder);

        //待回款额度
        BigDecimal thisMonthAmountReturned = opportunityDbService.selectAmountReturned(3,number,companyId,superAccountId);
        thisMonthOpp.setAmountReturned(thisMonthAmountReturned);

        //联系人新增
        Integer thisMonthNewContact = opportunityDbService.selectNewContact(3,number,companyId,superAccountId);
        thisMonthOpp.setNewContact(thisMonthNewContact);

        //电话量新增
        Integer thisMonthNewCallVolume = opportunityDbService.selectNewCallVolume(3,number,companyId,superAccountId);
        thisMonthOpp.setNewCallVolume(thisMonthNewCallVolume);

        //本月
        map.put("thisMonth",thisMonthOpp);

        return map;
    }

    /**
     * 商机合同占比
     * @param dateType //thisLastMonth 上月 thisWeek 本周  thisMonth 本月
     * @param bs 0 商机合同占比  1商机合同类型比例 2商机成交额比例
     * @return
     */
    @Override
    public List<OpportunityProductVO> oppContractProportion(String dateType,String bs) {

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String companyId =null;

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisLastMonth".equals(dateType)) {
                //上个月
                dateUnit = 1;
            }
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 2;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 3;
            }
        }

        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;

        if(rs) {
            number = 0;
            companyId = userAccount.getAccountId();
        }else {
            //普通管理员
            number = 1;
            companyId = userAccount.getCompanyId();
        }

        List<OpportunityProductVO> list = new ArrayList<>();
        //商机合同占比
        if("0".equals(bs)){
            list = opportunityDbService.oppContractProportion(dateUnit,number,companyId,superAccountId);
            //商机合同类型比例
        }else if("1".equals(bs)){
            list = opportunityDbService.oppContractTypeProportion(dateUnit,number,companyId,superAccountId);
            //商机成交额比例
        }else{
            list = opportunityDbService.oppTurnoverProportion(dateUnit,number,companyId,superAccountId);
        }

        //list为空做判断
        if(list.size() == 0){
            for(int i = 0;i<3;i++){
                OpportunityProductVO opportunityProductVO = new OpportunityProductVO();
                if(i ==0 || i==1){
                    if("0".equals(bs) || "2".equals(bs)) {
                        opportunityProductVO.setProductName(i+"");
                        opportunityProductVO.setProportion("0");
                        list.add(opportunityProductVO);
                    }
                    if("1".equals(bs)) {
                        opportunityProductVO.setProductName(i+1+"");
                        opportunityProductVO.setProportion("0");
                        list.add(opportunityProductVO);
                    }
                }

                if(i == 2) {
                    if("1".equals(bs)){
                        opportunityProductVO.setProductName(i+2+"");
                        opportunityProductVO.setProportion("0");
                        list.add(opportunityProductVO);
                    }
                }

            }


        }

        return list;
    }

    /**
     * 商机拥有数排行
     * @param bs 1赢单排行  2总数排行
     * @return
     */
    @Override
    public List<OpportunityOfNumberVO> oppOfNumber(Integer bs) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String companyId =null;
        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        //普通管理员
        if(!rs) {
            number = 1;
            companyId = userAccount.getCompanyId();
        }

        return opportunityDbService.oppOfNumber(bs,number,companyId,superAccountId);
    }

    /**
     * 商机状态个数跟进占比意向占比
     * @param dateType thisLastMonth 上月 thisWeek 本周  thisMonth 本月
     * @return
     */
    @Override
    public List<OpportunityFollowIntentionZbVO> opportunityFollowIntentionZb(String dateType) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String companyId =null;

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisLastMonth".equals(dateType)) {
                //上个月
                dateUnit = 1;
            }
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 2;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 3;
            }
        }

        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        //普通管理员
        if(!rs) {
            number = 1;
            companyId = userAccount.getCompanyId();
        }


        List<OpportunityFollowIntentionZbVO> list = opportunityDbService.opportunityFollowIntentionZb(dateUnit,number,companyId,superAccountId);
        List<OpportunityFollowIntentionZbVO> oppList = new ArrayList<>();
        Map<String, OpportunityFollowIntentionZbVO> map = list.stream().collect(Collectors.toMap(OpportunityFollowIntentionZbVO::getOpportunityStatus, OpportunityFollowIntentionZbVO -> OpportunityFollowIntentionZbVO));

        for (int i = 0; i < 7; i++) {
            OpportunityFollowIntentionZbVO opportunityFollowIntentionZbVO = new OpportunityFollowIntentionZbVO();
            if(map.containsKey(i+1+"")){
                opportunityFollowIntentionZbVO =  map.get(i+1+"");

                if(opportunityFollowIntentionZbVO.getZFollow() == null){
                    opportunityFollowIntentionZbVO.setFollowProportion("0");
                }
                if(opportunityFollowIntentionZbVO.getIntentionSixty() == null) {
                    opportunityFollowIntentionZbVO.setIntentionProportion("0");
                }
            }else{
                opportunityFollowIntentionZbVO.setOpportunityStatus(i+1+"");
                opportunityFollowIntentionZbVO.setStutsFollow(0+"");
                opportunityFollowIntentionZbVO.setFollowProportion("0");
                opportunityFollowIntentionZbVO.setIntentionProportion("0");
            }
            oppList.add(opportunityFollowIntentionZbVO);
        }
        return oppList;

    }

    /**
     * 商机管理-新增商机
     * @param addOpportunityQO 新增商机实体
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addOpportunity(AddOpportunityQO addOpportunityQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Opportunity opp = new Opportunity();
        String opportunityId = CommonUtils.getGUID();
        opp.setOpportunityId(opportunityId);
        opp.setOpportunityTitle(addOpportunityQO.getOpportunityTitle());
        //opp.setContactId(addOpportunityQO.getContactId());
        opp.setEstimatedSalesAmount(addOpportunityQO.getEstimatedSalesAmount());
        opp.setOpportunityStatus("1"); //商机状态 1: 初步洽谈 2: 需求确定 3: 方案报价 4: 谈判 5: 洽谈合同 6: 赢单 7: 输单
        opp.setOpportunityTp(addOpportunityQO.getOpportunityTp());  //商机类型 1:续费 2:新会员 3:单词 4:证书 5:线上单品 6:高端班 7:内训 8:咨询 9:其他
        opp.setOpportunitySource(addOpportunityQO.getOpportunitySource());
        opp.setCreatePeopleId(userAccount.getAccountId());
        opp.setCreateTm(new Date());
        opp.setUpdatePeopleId(userAccount.getAccountId());
        opp.setUpdateTm(new Date());
        opp.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        opp.setContactId(addOpportunityQO.getContactId());
        opp.setCustomerId(addOpportunityQO.getCustomerId());
        opp.setAccountId(userAccount.getAccountId());
        opp.setCompanyId(userAccount.getCompanyId());

        //新增商机产品
        List<OpportunityProduct> list = addOpportunityQO.getList();
        if(list.size() != 0){
            for(OpportunityProduct opportunityProduct : list){
                String opportunityProductId = CommonUtils.getGUID();
                opportunityProduct.setOpportunityProductId(opportunityProductId);
                opportunityProduct.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                opportunityProduct.setCreatePeopleId(userAccount.getAccountId());
                opportunityProduct.setCreateTm(new Date());
                opportunityProduct.setUpdatePeopleId(userAccount.getAccountId());
                opportunityProduct.setUpdateTm(new Date());
                opportunityProduct.setOpportunityId(opportunityId);
                opportunityProductDbService.addOpportunityProduct(opportunityProduct);
            }
        }

        //获取到公司名称
        //SysCompany sysCompany = sysCompanyService.selectSysCompanyById(userAccount.getCompanyId());

        //获取到登录人电话号
        //List<OpportunityCollaboratorVO> collList = opportunityCollaboratorDbService.userList(userAccount.getAccountId(),2);


        //新增协作人
        /*OpportunityCollaborator opportunityCollaborator = new OpportunityCollaborator();
        String opportunityCollaboratorId = CommonUtils.getGUID();
        opportunityCollaborator.setOpportunityCollaboratorId(opportunityCollaboratorId);
        opportunityCollaborator.setAccountId(userAccount.getAccountId());
        opportunityCollaborator.setUserName(userAccount.getUserName());
        if(sysCompany !=null) {
            if(!StringUtils.isBlank(sysCompany.getCompanyName())) {
                opportunityCollaborator.setCompanyName(sysCompany.getCompanyName());
            }
        }*/


        /*if(collList.size() !=0) {
            opportunityCollaborator.setContactInformation(collList.get(0).getContactInformation());
        }
        opportunityCollaborator.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        opportunityCollaborator.setOpportunityId(opportunityId);
        opportunityCollaboratorService.addOpportunityCollaborator(opportunityCollaborator);*/

        //新增商机联系人
        String opportunityContactId = CommonUtils.getGUID();
        OpportunityContact opportunityContact = new OpportunityContact();
        opportunityContact.setOpportunityContactId(opportunityContactId);
        opportunityContact.setContactName(addOpportunityQO.getContactName());
        opportunityContact.setContactPosition(addOpportunityQO.getContactPosition());
        opportunityContact.setContactInformation(addOpportunityQO.getContactInformation());
        opportunityContact.setContactType(0); //联系人类型-0首要联系人  1次要联系人
        opportunityContact.setAbolishState(1); //废止状态  1启动 2废止
        opportunityContact.setCreatePeopleId(userAccount.getAccountId());
        opportunityContact.setCreateTm(new Date());
        opportunityContact.setUpdatePeopleId(userAccount.getAccountId());
        opportunityContact.setUpdateTm(new Date());
        opportunityContact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        opportunityContact.setOpportunityId(opportunityId);
        opportunityContactService.addOpportunityContact(opportunityContact);



        //新增客户管理的商机
        Boolean result = opportunityDbService.addOpportunity(opp);
        return result;
    }

    /**
     * 商机管理-删除商机-修改商机删除标记
     * @param opportunityId
     * @return
     */
    @Override
    public Boolean updateOpportunity(String opportunityId) {
        Opportunity opportunity = opportunityDbService.selectByOpportunityId(opportunityId);
        opportunity.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
        return opportunityDbService.updateOpportunityId(opportunity);
    }

    /**
     * 修改回显
     * @param opportunityId
     * @return
     */
    @Override
    public OpportunityCustomerVO getOpportunityId(String opportunityId) {
        return opportunityDbService.getOpportunityId(opportunityId);
    }

    /**
     * 商机管理-修改商机
     * @param opportunity
     * @return
     */
    @Override
    public Boolean updateOpportunityId(Opportunity opportunity) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Opportunity opp = new Opportunity();
        opp.setOpportunityId(opportunity.getOpportunityId());
        /*opp.setOpportunityTitle(opportunity.getOpportunityTitle());
        opp.setCustomerProductId(opportunity.getCustomerProductId());
        opp.setOpportunityTheme(opportunity.getOpportunityTheme());
        opp.setContactId(opportunity.getContactId());
        opp.setOpportunityContact(opportunity.getOpportunityContact());
        opp.setOpportunityStatus(opportunity.getOpportunityStatus());
        opp.setLostOrderFriend(opportunity.getLostOrderFriend());
        opp.setEstimatedSigningTime(opportunity.getEstimatedSigningTime());
        opp.setLastFollowUpTime(opportunity.getLastFollowUpTime());
        opp.setNextFollowUpTime(opportunity.getNextFollowUpTime());
        opp.setEstimatedSalesAmount(opportunity.getEstimatedSalesAmount());
        opp.setPossibilitySigning(opportunity.getPossibilitySigning());
        opp.setOpportunityType(opportunity.getOpportunityType());
        opp.setOpportunityAcquisitionTime(opportunity.getOpportunityAcquisitionTime());
        opp.setOpportunitySource(opportunity.getOpportunitySource());
        opp.setRemarks(opportunity.getRemarks());*/
        opp.setOpportunityContractType("1");  //商机合同  0未创建  1创建
        opp.setUpdatePeopleId(userAccount.getAccountId());
        opp.setUpdateTm(new Date());
        //修改客户管理的商机
        Boolean result = opportunityDbService.updateOpportunity(opp);
        return result;
    }

    /**
     * 根据联系人id查询商机
     * @param pageIndex 页码
     * @param pageSize 条数
     * @param sortName 分组字段
     * @param sortOrder 分组类型
     * @param contactId 联系人id
     * @return
     */
    @Override
    public DhPageInfo<OpportunityVO> opportunityDetailList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String contactId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }


        List<OpportunityVO> opportunityList = opportunityDbService.opportunityDetailList(contactId, order.toString());

        PageInfo<OpportunityVO> pageInfo = new PageInfo<OpportunityVO>(opportunityList);
        return new DhPageInfo<OpportunityVO>(pageInfo, opportunityList);
    }

    /**
     * 商机-商机详情-通过商机id查询
     * @param opportunityId 商机id
     * @return
     */
    @Override
    public OpportunityVO opportunityDetail(String opportunityId) {
        CustomerContract customerContract = customerContractDbService.selectByOpportunityId(opportunityId);
        OpportunityVO opportunityVO = opportunityDbService.opportunityDetail(opportunityId);
        if(customerContract != null) {
            opportunityVO.setContractId(customerContract.getContractId());
        }
        return opportunityVO;

    }


    /**
     * @Description: 根据商机名称查询数据
     * @Param: [opportunityName]
     * @Return: java.util.List<com.crm.model.vo.datasearch.DataSearchResultVO>
     * @Author: lixq-f
     * @Date: 2021/5/13
     **/
    @Override
    public List<DataSearchResultVO> selectDataByOpportunityName(String opportunityName) {
        return opportunityDbService.selectDataByOpportunityName(opportunityName);
    }
}
